package com.yuan.springcloud.order.controller;

import com.yuan.springcloud.order.entity.Product;
import com.yuan.springcloud.order.feign.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author YouYuan
 * @version 1.0
 * @date 2020/3/25 6:13
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private DiscoveryClient discoveryClient; // 获取微服务列表的对象

    @Autowired
    private RestTemplate restTemplate; // Spring提供的发送HTTP调用远程服务的工具类

    @Autowired
    private ProductFeignClient productFeignClient; // Product微服务调用接口，使用Feign实现

    @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id) {
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");//获取服务列表
//        ServiceInstance instance = instances.get(0);
//        String serverUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + id;
        String serverUrl = "http://service-product/product/" + id;//直接使用服务名，依靠Ribbon实现远程服务调用
//        Product product = restTemplate.getForObject(serverUrl, Product.class);
        Product product = productFeignClient.findById(id);//使用Feign调用微服务
        return product;
    }

    @RequestMapping(value = "/msg", method = RequestMethod.GET)
    public String msg(String msg) {
        return productFeignClient.msg(msg);
    }
}
